package com.common;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class ChangeResponseFilter implements Filter {

    @Override
    public void destroy() {
        // TODO Auto-generated method stub
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain arg2)
            throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String currentURL = request.getRequestURI();
        String ctxPath = request.getContextPath();
        // 除掉项目名称时访问页面当前路径
        String targetURL = currentURL.substring(ctxPath.length());
        HttpSession session = request.getSession(false);
        // 对当前页面进行判断，如果当前页面不为登录页面
        if (!("/login.jsp".equals(targetURL)) && !(targetURL.contains("/LoginServlet"))
                && !(targetURL.indexOf("/img") == 0) && !(targetURL.contains("/visit"))
                && !(targetURL.contains("/VisitServlet")) && !(targetURL.contains("/javascript"))
                && !(targetURL.contains("/info")) && !(targetURL.contains("/HtmlServlet"))) {
            // 在不为登陆页面时，再进行判断，如果不是登陆页面也没有session则跳转到登录页面，
            if (session == null || session.getAttribute("user") == null) {
                request.getRequestDispatcher("/login.jsp").forward(request, response);
                return;
            } else {
                request.getRequestDispatcher(targetURL).forward(request, response);
                return;
            }
        } else {
            request.getRequestDispatcher(targetURL).forward(request, response);
            return;
        }
    }

    @Override
    public void init(FilterConfig arg0) throws ServletException {
        // TODO Auto-generated method stub
    }

}
